package com.liuss.springchatai.controller;

import com.liuss.springchatai.data.OrderRecord;
import com.liuss.springchatai.service.OrderRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;


/**
 * @Author: lss
 * @Date: 2025-04-11-15:30
 * @Description:
 */
@RestController
@RequestMapping("/ai")
@Slf4j
public class OpenAiController {


    @Resource
    private OrderRecordService orderRecordService;

    @Resource
    private ChatClient chatClient;

    @Autowired
    private ChatMemory chatMemory;

    @Resource
    private VectorStore vectorStore;

    // 对话记忆长度
    private final Integer CHAT_HISTORY_SIZE = 10;

    @GetMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> ragJsonText(@RequestParam(value = "message", defaultValue = "你好.") String message,
                                    @RequestParam(value = "userId", defaultValue = "2410401870") String userId) {

        Flux<String> content = chatClient
                .prompt()
                .functions("refund", "query")//function函数调用
                .advisors(
                        new MessageChatMemoryAdvisor(chatMemory, userId, CHAT_HISTORY_SIZE)//对话记忆
                        ,new QuestionAnswerAdvisor(vectorStore)//RAG向量数据库
                )
                .user(message)
                .stream()//流式输出
                .content();
        return content.concatWith(Flux.just("[complete]"));
    }

    @GetMapping("/exam/list")
    public List<OrderRecord> list() {
        return orderRecordService.list();
    }

    @PostMapping("/edit")
    public boolean edit(@RequestBody OrderRecord orderRecord) {
        orderRecordService.edit(orderRecord);
        return true;
    }

}
